#pragma comment(lib, "glew32.lib")
#pragma comment(lib, "freeglut.lib")
#pragma comment(lib, "soil.lib")

#include <stdio.h>
#include <gl/glew.h>
#include <gl/glut.h>
#include <gl/soil.h>
#include <gl/freeglut_ext.h>
#include <iostream>

int windowWidth = 0;
int windowHeight = 0;


const GLenum PIXEL_FORMAT = GL_BGRA;
const int IMAGE_WIDTH = 1024;
const int IMAGE_HEIGHT = 1024;
const int SCREEN_WIDTH = 400;
const int SCREEN_HEIGHT = 300;
const int CHANNEL_COUNT = 4;
const int DATA_SIZE = IMAGE_WIDTH * IMAGE_HEIGHT * CHANNEL_COUNT;

GLuint pboIds[2];
GLuint textureId;
GLubyte* imageData = 0;


void ChangeSize(int w, int h)
{
	windowWidth = w;
	windowHeight = h;

	if (h == 0)
		h = 1;
	glViewport(0, 0, w, h);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0, w*1.0 / h, 0.01, 1000.0f);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void SetupRC()
{
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glPixelStorei(GL_PACK_ALIGNMENT, 1);
	glPixelStorei(GL_PACK_SWAP_BYTES, TRUE);

	glGenTextures(1, &textureId);
	glBindTexture(GL_TEXTURE_2D, textureId);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, IMAGE_WIDTH, IMAGE_HEIGHT, 0,
		PIXEL_FORMAT, GL_UNSIGNED_BYTE, (GLvoid*)imageData);
	glBindTexture(GL_TEXTURE_2D, 0);

	glGenBuffers(2, pboIds);
	glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboIds[0]);
	glBufferData(GL_PIXEL_UNPACK_BUFFER, DATA_SIZE, 0, GL_STREAM_DRAW);
	glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboIds[1]);
	glBufferData(GL_PIXEL_UNPACK_BUFFER, DATA_SIZE, 0, GL_STREAM_DRAW);
	glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);

	imageData = new GLubyte[DATA_SIZE];
	memset(imageData, 0, DATA_SIZE);
}

void RenderScene(void)
{
	static int index = 0;
	int nextindex = 0;

	glBindTexture(GL_TEXTURE_2D, textureId);
	glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pboIds[index]);

	glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, IMAGE_WIDTH,
		IMAGE_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, 0);







	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

	glLoadIdentity();
	glTranslated(0, 0, -2);
	//drawCube();

	glutSwapBuffers();
}


void KeyboardCB(unsigned char key, int x, int y)
{

}


int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
	glutInitWindowSize(400, 300);
	glutCreateWindow("OpenGL");
	glutReshapeFunc(ChangeSize);
	glutDisplayFunc(RenderScene);
	glutKeyboardFunc(KeyboardCB);

	GLenum err = glewInit();
	if (GLEW_OK != err) {
		fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
		return 1;
	}

	SetupRC();

	glutMainLoop();

	delete[] imageData;
	imageData = 0;

	glDeleteTextures(1, &textureId);

	glDeleteBuffersARB(2, pboIds);

	return 0;
}